<template>
  <a-modal
    v-model:open="openAddSpace"
    title="新增空间"
    ok-text="保存"
    cancel-text="取消"
    @ok="addSpace"
  >
    <a-form layout="horizontal" :model="addSpaceParam" style="max-width: 600px">
      <a-form-item label="空间昵称">
        <a-input v-model:value="addSpaceParam.spaceName" placeholder="输入昵称" allow-clear />
      </a-form-item>

      <a-form-item label="空间级别">
        <a-select
          v-model:value="addSpaceParam.spaceLevel"
          placeholder="选择空间级别"
          :options="SPACE_LEVEL_OPTIONS"
          allow-clear
        >
        </a-select>
      </a-form-item>
      <a-card title="空间级别介绍" style="padding: 0">
        <a-typography-paragraph>
          * <a href="#" target="_blank">管理员</a> 可创建所有级别的空间。
        </a-typography-paragraph>
        <a-typography-paragraph v-for="spaceLevel in spaceLevelList">
          {{ spaceLevel.text }}： 大小 {{ formatSize(spaceLevel.maxSize) }}， 数量
          {{ spaceLevel.maxCount }}
        </a-typography-paragraph>
      </a-card>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">

import { onMounted, ref } from 'vue'
import { addSpaceUsingPost, listSpaceLevelUsingPost } from '@/api/spaceController.ts'
import { message } from 'ant-design-vue'
import { SPACE_LEVEL_OPTIONS } from '@/constants/space.ts'
import { formatSize } from '../../../utils'


// 获取父组件方法
const emit = defineEmits(['refresh'])

// 打开对话框
const openAddSpace = ref(false)
const openDialog = () => {
  addSpaceParam.value = {
    spaceName: '',
    spaceLevel: 0
  }
  openAddSpace.value = true
}

// 添加空间所需参数
let addSpaceParam = ref<API.SpaceAddRequest>({})

// 添加空间
const addSpace = async () => {
  const res = await addSpaceUsingPost(addSpaceParam.value)
  // 添加成功将参数置零
  if (res.data.code === 0 && res.data.data) {
    addSpaceParam.value = {
      spaceName: '',
      spaceLevel: 0
    }
    openAddSpace.value = false
    message.success('添加成功')
    await emit('refresh')
  } else {
    message.error('添加失败，' + res.data.message)
  }
  openAddSpace.value = false
}

// 获取空间级别

const spaceLevelList = ref<API.SpaceLevel[]>([])
const getSpaceLevelList = async () => {
  const res = await listSpaceLevelUsingPost()
  if (res.data.code === 0 && res.data.data){
    spaceLevelList.value = res.data.data
  }else {
    message.error("加载空间级别失败，" + res.data.message)
  }
}

// 暴露方法给父类
defineExpose({
  openDialog
});

onMounted(() => {
  getSpaceLevelList()
})

</script>

<style scoped>


</style>
